package com.eastfair.config.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eastfair.auth.entity.Organization;
import com.eastfair.config.dao.TableMapper;
import com.eastfair.config.entity.FormField;
import com.eastfair.config.service.FormFieldService;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.context.ContextUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * <p>
 * 前端控制器
 *
 * </p>
 *
 * @author ligang
 * @date 2021-07-23
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/table")
@Api(value = "table", tags = "")
public class TableController {
    private Pattern linePattern = Pattern.compile("_(\\w)");
    @Autowired
    private TableMapper tableMapper;

    @Autowired
    private FormFieldService formFieldService;

    /**
     * 数据表结构
     *
     * @param tableName 数据表结构
     * @return
     *
     * http://localhost:9011/config/table/tableInfo?tableName=e_exhibitor&className=Exhibitor&subjectType=ACTOR
     * header: exhibitionid 1
     *
     */
    @ApiOperation(value = "数据表结构", notes = "数据表结构")
    @GetMapping("/tableInfo")
    public boolean tableInfo(String tableName, String className,String subjectType) {
        List<Map> map = tableMapper.listTableColumn(tableName);
        execute(map,className,subjectType);
        return true;
    }


    /**
     * 下划线转驼峰
     */
    public String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }


    public void execute(List<Map> map, String className,String subjectType) {
        //过滤字段
        List<String> filerColumn = Arrays.asList(
                "project_id",
                "created_by",
                "create_time",
                "updated_by",
                "update_time",
                "is_enabled",
                "is_deleted"
        );

        for (Map map1 : map) {
            String column1 = (String) map1.get("COLUMN_NAME");
            String columnName = lineToHump(column1);
            if(filerColumn.contains(column1)||  "id".equals(column1)){
                continue;
            }
            String columnComment = (String) map1.get("COLUMN_COMMENT");
            System.out.println(columnName+","+columnComment);
            QueryWrapper<FormField> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(FormField::getKeyword, columnName);
            queryWrapper.lambda().eq(FormField::getClassName, className);
            queryWrapper.lambda().eq(FormField::getIsDeleted, BusinessConstant.NO);
            List<FormField> formFieldList = formFieldService.list(queryWrapper);

            FormField formFieldEn = new FormField();
            FormField formFieldCn = new FormField();
            if(formFieldList!=null && !formFieldList.isEmpty()){
                for(FormField formField : formFieldList){
                    if("CN".equals(formField.getLanguageType())){
                        formFieldCn = null;
                    }else if("EN".equals(formField.getLanguageType())){
                        formFieldEn = null;
                    }
                }
            }

            if(formFieldEn!=null){
                formFieldEn.setProjectId(ContextUtil.getProjectId());
                formFieldEn.setExhibitionId(ContextUtil.getExhibitionId());
                formFieldEn.setSubjectType(subjectType);
                formFieldEn.setLanguageType("EN");
                formFieldEn.setFieldName(columnComment);
                formFieldEn.setKeyword(columnName);
                formFieldEn.setClassName(className);
                executeSave(formFieldEn);
            }
            if(formFieldCn!=null){
                formFieldCn.setProjectId(ContextUtil.getProjectId());
                formFieldCn.setExhibitionId(ContextUtil.getExhibitionId());
                formFieldCn.setSubjectType(subjectType);
                formFieldCn.setLanguageType("CN");
                formFieldCn.setFieldName(columnComment);
                formFieldCn.setKeyword(columnName);
                formFieldCn.setClassName(className);
                executeSave(formFieldCn);
            }
        }
    }
    private void executeSave(FormField formField){
        formFieldService.saveOrUpdate(formField);

    }
}
